package com.qsw.datetimepickerlib.DateTimePicker.view;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Pair;

class DTPLUtil {
    private static final Handler mHandler = new Handler(Looper.getMainLooper());

    private DTPLUtil() {
    }

    /**
     * 运行在主线程
     *
     * @param runnable 要运行的代码
     */
    public static void runOnUIThread(Runnable runnable) {
        mHandler.post(runnable);
    }

    /**
     * 根据年和月获取该月有几天
     *
     * @param year  年
     * @param month 月
     * @return 该月一共有几天
     */
    public static int getDayNumOfMonth(int year, int month) {
        int day = 0;
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            day = 29;
        } else {
            day = 28;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                return day;
        }
        return 0;
    }

    /**
     * 获取字符串宽高，宽高都恰好包裹字符串
     *
     * @param text  要测试的字符串
     * @param paint 测试使用的画笔
     * @return 若字符串为空则返回null，否则返回Pair-width, height
     */
    public static Pair<Integer, Integer> getTextSize(String text, Paint paint) {
        if (TextUtils.isEmpty(text)) {
            return null;
        }
        Rect rect = new Rect();
        paint.getTextBounds(text, 0, text.length(), rect);
        return new Pair<>(rect.width(), rect.height());
    }

    /**
     * dp转px
     *
     * @param context 环境
     * @param dpValue dp
     * @return px
     */
    public static int dp2px(Context context, float dpValue) {
        return (int) (dpValue * context.getResources().getDisplayMetrics().density + 0.5f);
    }
}
